angular.module('Controller')
.controller('QgyCotenantModalCtrl',($scope,urls,$localStorage,qgyApiService,$rootScope,NgTableParams,commonUtil,cryptUtil,wfAlert,commonConstant,$http, $uibModalInstance, items)->
    $scope.type=type=items.type
    $scope.cotenant=items.data
    $scope.modalTitle=if type=='view' then '查看住客' else '编辑住客'
    $scope.modalSexList=commonConstant.numSexList()
    $scope.modalAllSexList=commonConstant.qgySexList()
    $scope.tableParams = new NgTableParams(
            {page: 1, count: commonConstant.pageTableCount},
            {
                counts: [],
                getData: ($defer, params)->
                    $defer.resolve($scope.cotenant)
                    #123213
                    params.total($scope.cotenant.length)
                    return ;
            }
    )
    $scope.new={sex:1}
    imageUpData=[
        {id:'#cco-idcard-front',paramName:'cardFront'}
        {id:'#cco-idcard-back',paramName:'cardBack'}
    ]
    $scope.uploadImageData=(eleId)->
        qgyApiService.bindImageUploadAndGenApi(eleId)
        $(eleId).click()
        ''
    $rootScope.$on('qgy-image-upload',(val,data)->
        return if imageUpData==undefined
        tmp=_.find(imageUpData,(item)->item.id==data.eleId)
        object=$scope.new
        if(tmp and object)
            object[tmp.paramName]=data.pictureUrl
    )
    _.extend $scope,
        newPerson: ()->
            if _.some($scope.cotenant,(item)->item.customerCard==$scope.new.customerCard)
                wfAlert.toastInfo('身份证不能重复')
                return
            data=angular.copy($scope.new)
            $scope.cotenant.push(data)
            $scope.new={sex:1}
            $scope.tableParams.reload()
            ''
        editPerson:(item)->
            tmp=_.find($scope.cotenant,(theItem)->theItem.customerCard==item.customerCard)
            if tmp
                $scope.editingItem=angular.copy(tmp)
                $scope.new=angular.copy(tmp)
            ''
        cancelEdit:()->
            $scope.editingItem=undefined
            $scope.new={sex:1}
        saveEdit:()->
            if _.some($scope.cotenant,(item)->item.customerCard==$scope.new.customerCard and item.customerCard!=$scope.editingItem?.customerCard)
                wfAlert.toastInfo('身份证不能重复')
                return
            $scope.cotenant=_.filter($scope.cotenant,(theItem)->theItem.customerCard!=$scope.editingItem?.customerCard)
            $scope.editingItem=undefined
            data=angular.copy($scope.new)
            $scope.cotenant.push(data)
            $scope.new={}
            $scope.tableParams.reload()
            ''
        removePerson: (item)->
            $scope.cotenant=_.filter($scope.cotenant,(theItem)->theItem.customerCard!=item.customerCard)
            $scope.tableParams.reload()
            ''
    $scope.confirm = ()->
        $uibModalInstance.close($scope.cotenant)
    $scope.cancel =()->
        $uibModalInstance.dismiss('cancel')
)